package com.baoyouqun.API.IM;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.cola.dto.Response;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.fastjson2.JSONObject;
import com.baoyouqun.entity.User;
import com.baoyouqun.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;


/**
 * 腾讯IM相关接口（供小程序调用）
 */
@RestController
public class ImController {

    @Resource
    private UserService userService;

    @Resource
    private ImConfig imConfig;

    @Resource
    private TencentImService tencentImService;

    /**
     * 初始化IM用户（导入用户到腾讯IM）
     */
    @PostMapping("/im/initUser")
    public Response initIMUser() {
        try {
            String userId = StpUtil.getLoginIdAsString(); // 业务用户ID
            User userEntity = userService.getById(userId);
            if (userEntity == null) {
                return Response.buildFailure("100404", "未查询到该用户信息");
            }

            // 1. 生成管理员UserSig（修复之前的错误：用TLSSigAPIv2生成签名，而非直接用adminUserId）
            TLSSigAPIv2 tlsSigAPI = new TLSSigAPIv2(imConfig);
            String adminSig = tlsSigAPI.genUserSig(imConfig.getAdminUserId(), 86400);

            // 2. 构建腾讯IM用户创建接口URL
            String imCreateUserUrl = "https://console.tim.qq.com/v4/im_open_login_svc/account_import" +
                    "?sdkappid=" + imConfig.getSdkAppId() +
                    "&identifier=" + imConfig.getAdminUserId() +
                    "&usersig=" + adminSig +
                    "&random=99999999&contenttype=json";

            // 3. 构建请求体（用业务用户ID作为IM的Identifier）
            JSONObject requestBody = new JSONObject();
            String imUserId = userId; // 核心：IM用户ID与业务用户ID保持一致
            requestBody.put("UserID", imUserId);
            requestBody.put("Nick", userEntity.getName() != null ? userEntity.getName() : "");
            requestBody.put("FaceUrl", userEntity.getHeadImg() != null ? userEntity.getHeadImg() : "");

            // 4. 调用腾讯IM接口创建用户
            String response = HttpUtil.post(imCreateUserUrl, requestBody.toString());
            JSONObject result = JSONObject.parseObject(response);
            if (result.getIntValue("ErrorCode") != 0) {
                return Response.buildFailure("100402", "初始化IM用户失败：" + result.getString("ErrorInfo"));
            }
            result.put("imUserId", imUserId);
            // 5. 绑定：将IM用户ID存入业务用户表（关键步骤）
            userService.bindImId(userId, imUserId); // 调用UserServiceImpl的bindImId方法

            return SingleResponse.of(result);
        } catch (Exception e) {
            return Response.buildFailure("100403", "初始化IM用户异常：" + e.getMessage());
        }
    }

    /**
     * 获取UserSig（供小程序使用）
     */
    @GetMapping("/im/getUserSig")
    public Response getUserSig() {
        try {
            String userId = StpUtil.getLoginIdAsString();
            String userSig = new TLSSigAPIv2(imConfig).genUserSig(userId, 86400); // 24小时有效期
            return SingleResponse.of(userSig);
        } catch (Exception e) {
            return Response.buildFailure("100401", "获取UserSig失败：" + e.getMessage());
        }
    }

    /**
     * 发送系统消息
     *
     * @param toUserId 接收消息的用户ID
     * @param content  消息内容
     */
    @PostMapping("/im/sendSystemMsg")
    public Response sendSystemMessage(@RequestParam String toUserId, @RequestParam String content) {
        try {
            // 系统消息通常由管理员发送
            String adminUserId = imConfig.getAdminUserId();
            JSONObject result = tencentImService.sendSystemMessage(adminUserId, toUserId, content);

            if (result.getIntValue("ErrorCode") != 0) {
                return Response.buildFailure("100405", "发送消息失败：" + result.getString("ErrorInfo"));
            }
            return SingleResponse.of(result);
        } catch (Exception e) {
            return Response.buildFailure("100406", "发送消息异常：" + e.getMessage());
        }
    }

    /**
     * 接收腾讯IM回调（需在腾讯云控制台配置回调地址）
     */
    @PostMapping("/im/callback")
    public JSONObject receiveCallback(
            HttpServletRequest request,
            @RequestHeader("x-tls-sigature") String signature,
            @RequestParam("nonce") String nonce,
            @RequestParam("timestamp") String timestamp,
            @RequestBody String body) {

        // 1. 验证签名
        boolean isVerified = tencentImService.verifyCallbackSignature(signature, nonce, timestamp, body);
        if (!isVerified) {
            return buildCallbackResponse(1, "签名验证失败");
        }

        // 2. 解析回调内容（根据实际业务处理，例如：消息回调、状态变更等）
        JSONObject callbackData = JSONObject.parseObject(body);
        String eventType = callbackData.getString("Event");
        // 示例：处理消息发送回调
        if ("C2C_MSG_RECEIVE".equals(eventType)) {
            // 业务逻辑处理...
            System.out.println("收到单聊消息：" + callbackData);
        }

        // 3. 返回成功响应（腾讯IM要求必须返回此格式）
        return buildCallbackResponse(0, "success");
    }

    // 构建回调响应
    private JSONObject buildCallbackResponse(int errorCode, String errorInfo) {
        JSONObject response = new JSONObject();
        response.put("ActionStatus", errorCode == 0 ? "OK" : "FAIL");
        response.put("ErrorCode", errorCode);
        response.put("ErrorInfo", errorInfo);
        return response;
    }


}